// pages/user/user.js
const call = require('../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: '/images/default.jpg',
    nickName: '神秘人',
    school: '',
    editTip: '设置后不可修改',
    editing: false
  },
  editSchool: function(){
    this.setData({
      editing: true
    })
  },
  cancel: function() {
    this.setData({
      editing: false,
      editTip: '设置后不可修改'
    })
  },
  confirm: function(e){
    const that = this
    const school = e.detail.value.school.replace(/\s+/g, '')
    if (!school) {
      that.setData({
        editTip: '请输入学校！'
      })
    } else {
      const openId = wx.getStorageSync('token');
      const school = e.detail.value.school;
      const avatar = that.data.avatar;
      const nickName = that.data.nickName;
      if(openId){
        call.requestPost('user/updateUser', {
          openId: openId,
          school: school,
          nickName: nickName
        }, function (e) {
          console.log(e)
          that.setData({
            school: school,
            editing: false
          })
          wx.showToast({
            title: '设置成功',
            icon: 'success',
            duration: 2000
          })
        }, function () {

        });
      } else {
        wx.navigateTo({
          url: '../authPage/authPage'
        })
      }
    }
  },
  setSchool: function() {
    wx.showToast({
      title: '敬请期待新功能；）',
      icon: 'none',
      duration: 2000
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const openId = wx.getStorageSync('token');
    const that = this
    if (openId) {
      call.requestGet('user/findUser', {
        openId: openId
      }, function (e) {
        console.log('userDetail', e)
        that.setData({
          avatar: e.avatar,
          nickName: e.nickName,
          school: e.school
        })
      }, function () {

      });
    } else {
      wx.redirectTo({
        url: '../authPage/authPage?page=user'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})